package org.hbkj.springbootmybatis.controller;

import org.hbkj.springbootmybatis.entity.ShoppingCartDo;
import org.hbkj.springbootmybatis.service.ShoppingCartService;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/shoppingcart")
public class ShoppingCartController {

    private final ShoppingCartService shoppingCartService;

    public ShoppingCartController(ShoppingCartService shoppingCartService) {
        this.shoppingCartService = shoppingCartService;
    }

    // 获取用户购物车列表
    @GetMapping
    public List<ShoppingCartDo> getCartList(@RequestParam("userid") Integer userId) {
        return shoppingCartService.getCartListByUserId(userId);
    }

    // 添加商品到购物车
    @PostMapping
    public String addToCart(
            @RequestParam("userid") Integer userId,
            @RequestParam("goodsid") Integer goodsId,
            @RequestParam("quantity") Integer quantity,
            @RequestParam("price") Double price) {
        ShoppingCartDo cartDo = new ShoppingCartDo();
        cartDo.setUserid(userId);
        cartDo.setGoodsid(goodsId);
        cartDo.setQuantity(quantity);
        cartDo.setTotalamount(new BigDecimal(price * quantity));
        shoppingCartService.addToCart(cartDo);
        return "添加成功";
    }

    // 更新购物车商品数量
    @PutMapping
    public String updateQuantity(
            @RequestParam("cartid") Integer cartId,
            @RequestParam("userid") Integer userId,
            @RequestParam("quantity") Integer quantity,
            @RequestParam("totalamount") Double totalAmount) {
        shoppingCartService.updateQuantity(cartId, userId, quantity, totalAmount);
        return "更新成功";
    }

    // 删除购物车商品
    @DeleteMapping
    public String deleteCartItem(
            @RequestParam("cartid") Integer cartId,
            @RequestParam("userid") Integer userId) {
        shoppingCartService.deleteCartItem(cartId, userId);
        return "删除成功";
    }
}